package com.io.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * The class/interface
 *
 * @author guod
 * @version 1.0 use jdk 1.8
 */
@Slf4j
public class TokenUtils {
    // JWT密码
    @Value("${token.secret}")
    private static final String secret = "guo";

    // 20 * 24 * 60 * 60 * 1000;  5天
    @Value("${token.expiration}")
    private static final Long expiration = 20 * 24 * 60 * 60 * 1000L;

    /**
     * 根据 claims 生成 Token
     */
    private static String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject("userId")
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(SignatureAlgorithm.HS512, secret.getBytes(StandardCharsets.UTF_8))
                .compact();
    }

    /**
     * 解析 token 的主体 Claims
     */
    private static Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret.getBytes(StandardCharsets.UTF_8))
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    public static void main(String[] args) {
        String s = generateToken(new HashMap<>());
        System.out.println(s);
        System.out.println(getClaimsFromToken(s));
        Claims claimsFromToken = getClaimsFromToken(s);
        System.out.println(claimsFromToken.getExpiration());
    }

}
